import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: 'http://localhost:8000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          ElMessage.error('登录已过期，请重新登录')
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('没有权限访问此资源')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 422:
          const errorMsg = data.detail?.map(err => err.msg).join(', ') || '请求参数错误'
          ElMessage.error(errorMsg)
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data.message || data.detail || '请求失败')
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 认证相关API
export const authAPI = {
  login: (username, password) => {
    return api.post('/auth/login', { username, password })
  },
  
  getCurrentUser: () => {
    return api.get('/auth/me')
  },
  
  logout: () => {
    return api.post('/auth/logout')
  },
  
  refreshToken: () => {
    return api.post('/auth/refresh')
  }
}

// 商品数据相关API
export const productAPI = {
  // 获取商品数据列表
  getProducts: (params = {}) => {
    return api.get('/products/', { params })
  },
  
  // 添加商品数据
  createProduct: (data) => {
    return api.post('/products/', data)
  },
  
  // 删除商品数据
  deleteProduct: (id) => {
    return api.delete(`/products/${id}`)
  },
  
  // 获取商品类别列表
  getCategories: () => {
    return api.get('/products/categories')
  },
  
  // 获取统计信息
  getStats: () => {
    return api.get('/products/stats')
  },
  
  // 获取商品类别统计
  getCategoryStats: () => {
    return api.get('/products/stats/categories')
  },
  
  // 获取价格分布统计
  getPriceStats: () => {
    return api.get('/products/stats/prices')
  },
  
  // 更新商品数据
  updateProduct: (id, data) => {
    return api.put(`/products/${id}`, data)
  }
}

export default api